package com.acoreful.acf2java.admin.modules.auth.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.acoreful.acf2java.admin.modules.auth.model.AuthUser;
import com.acoreful.acf2java.admin.modules.auth.service.AuthService;
import com.acoreful.acf2java.admin.modules.auth.service.CaptchaService;
import com.acoreful.acf2java.admin.modules.auth.support.CurrentStaff;
import com.acoreful.acf2java.admin.modules.auth.support.annotation.Subject;
import com.acoreful.acf2java.commons.base.WebBaseController;
import com.acoreful.acf2java.commons.beans.model.Response;
import com.acoreful.acf2java.commons.utils.HttpServletUtils;

/**
 *	登录
 */
@RequestMapping("/login")
@Controller
public class LoginController extends WebBaseController{
    
    @Autowired
    private CaptchaService captchaService;
    
    @Autowired
    private AuthService authService;
    
    @RequestMapping(method = RequestMethod.GET)
    public String index(@Subject(required = false) CurrentStaff currentStaff, Model model) {
        model.addAttribute("captchaToken", RandomStringUtils.randomAlphanumeric(16));
        return "login";
    }
    
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public Response<String> login(String username, String password, String captchaToken, 
            String captcha, HttpServletRequest request, HttpServletResponse response) {
        if (!captchaService.validate(captchaToken, captcha)) {
            return Response.response(100, "验证码错误", null);
        }
        
        AuthUser authUser= authService.login(username, password);
        if (authUser == null) { // 登录成功
        	return fail(101, "用户名或密码不正确");
        }
        HttpServletUtils.addCookieToResponse(request, response, AuthService.ACCESS_TOKEN, authUser.getAccessToken());
        return successData(null);
    }
    
}
